Skip to content

Allow Type reference instead of Class reference in RestTemplate's convenience methods. #35301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

sam-hieken
Copy link

@sam-hieken sam-hieken commented Aug 9, 2025

Issue

The convenience methods *ForEntity and *ForObject in RestTemplate don't allow generic types to be specified in the result body. For example:

public class Main {
	static class ExampleType {
		...
	}

	public static void main(String[] args) {
		RestTemplate restTemplate = ...;
		URI url = ...;
		
                // Type mismatch: cannot convert from ResponseEntity<List> to ResponseEntity<List<Main.ExampleType>>
		ResponseEntity<List<ExampleType>> result = restTemplate.getForEntity(url, List.class);
        }
}

Using Type as the type of the responseType parameters instead of Class<T> in these methods would allow generic types to be used as well (and since Class extends Type, changing it wouldn't be a breaking change):

public class Main {
	static class ExampleType {
		...
	}
	
	public static void main(String[] args) {
		RestTemplate restTemplate = ...;
		URI url = ...;
		
		// Example of how we can now allow generic types using com.fasterxml.jackson.core.type.TypeReference
		ResponseEntity<List<ExampleType>> result = restTemplate.getForEntity(url, new TypeReference<List<ExampleType>>() {}.getType());
}

@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Aug 9, 2025
@sam-hieken sam-hieken force-pushed the resttemplate-allow-generic-types branch from b0cd03d to 6b1a55b Compare August 9, 2025 22:26
@bclozel
Copy link
Member

bclozel commented Aug 10, 2025

Thanks for the proposal but this is well supported already with ParameterizedTypeReference, see https://docs.spring.io/spring-framework/reference/integration/rest-clients.html#rest-resttemplate

Also I don't think this change would have the desired behavior as the generic type information is probably not handled by messages readers in this way.

Thanks!

@bclozel bclozel closed this Aug 10, 2025
@bclozel bclozel added status: declined A suggestion or change that we don't feel we should currently apply and removed status: waiting-for-triage An issue we've not yet triaged or decided on labels Aug 10, 2025
@sam-hieken
Copy link
Author

Thanks for taking a look Brian

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: declined A suggestion or change that we don't feel we should currently apply
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants